import axios from 'axios'
import {i18nInstance } from '@/plugin/i18n'
import { useUserStore } from '@/stores/user/index.js' // 直接引入 i18n 实例
const getI18n = () => {
  if (!i18nInstance?.global) {
    throw new Error('i18n 未初始化！请确保在调用请求前初始化 i18n。')
  }
  return i18nInstance
}

const _t = (key) => getI18n().global.t(key)
/**
 * 初始化
 */

let _axios = null
export const baseURL = window.VUE_APP_BASE_API
// export const initAxios = () => {
if (!_axios) {
  _axios = axios.create({
    // 默认请求连接
    baseURL: baseURL,
    // 请求头
    headers: {
      'Content-Type': 'application/json',
    },
    // 超时时间（ms）
    timeout: 10 * 1000
  })
}
// }
// 请求拦截器
_axios.interceptors.request.use((config) => {
  // token 判断
  let userStore = useUserStore()
  let token = userStore.token
  if (token) {
    config.headers['Authorization'] = token
    config.headers['token'] = token
  }
  config.headers['language'] = document.querySelector('html').getAttribute('language')
  config.headers['Lang'] = document.querySelector('html').getAttribute('lang')

  return config
})

// 响应拦截器
_axios.interceptors.response.use((response) => {
  if (response.status === 200) {
    const resCode = response.data.code
    if (response.data && resCode > 0) {
      return Promise.resolve(response.data)
    } else {
      console.log(response.data.msg || 'System error')
      return Promise.reject(response)
    }
  } else {
    console.log('Network anomaly')
    return Promise.resolve(response)
  }
})

/**
 * post 请求
 */
export const post = (url, params) => _axios.post(url, params)

/**
 * get 请求
 */
export const get = (url, params) => _axios.get(url, params)
